package com.mzba.place.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.util.Log;
/**
 * 
 * @author 06peng
 *
 */
public class ImageThumbnail {

	//计算缩放比
    public static float reckonThumbnail(int oldWidth, int oldHeight, int newWidth, int newHeight) {
        if ((oldHeight > newHeight && oldWidth > newWidth)
                || (oldHeight <= newHeight && oldWidth > newWidth)) {
            float be = (float) (oldWidth / (float) newWidth);
            if (be <= 1)
                be = 1;
            return be;
        } else if (oldHeight > newHeight && oldWidth <= newWidth) {
            float be = (float) (oldHeight / (float) newHeight);
            if (be <= 1)
                be = 1;
            return be;
        }

        return 1;
    }

    /**
     * @param photoPath --原图路经
     * @param aFile     --保存缩图
     * @param newWidth  --缩图宽度
     * @param newHeight --缩图高度
     */
    public static boolean bitmapToFile(String photoPath, File aFile, int newWidth, int newHeight) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        // 获取这个图片的宽和高
        Bitmap bitmap = BitmapFactory.decodeFile(photoPath, options);
        options.inJustDecodeBounds = false;
 
        //计算缩放比
        options.inSampleSize = (int) reckonThumbnail(options.outWidth, options.outHeight, newWidth, newHeight);

        bitmap = BitmapFactory.decodeFile(photoPath, options);

        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            byte[] photoBytes = baos.toByteArray();

            if (aFile.exists()) {
                aFile.delete();
            }
            aFile.createNewFile();

            FileOutputStream fos = new FileOutputStream(aFile);
            fos.write(photoBytes);
            fos.flush();
            fos.close();

            return true;
        } catch (Exception e1) {
            e1.printStackTrace();
            if (aFile.exists()) {
                aFile.delete();
            }
            Log.e("Bitmap To File Fail", e1.toString());
            return false;
        }
    }

    public static Bitmap PicZoom(Bitmap bmp, int width, int height) {
        int bmpWidth = bmp.getWidth();
        int bmpHeght = bmp.getHeight();
        Matrix matrix = new Matrix();
        matrix.postScale((float) width / bmpWidth, (float) height / bmpHeght);

        return Bitmap.createBitmap(bmp, 0, 0, bmpWidth, bmpHeght, matrix, true);
    }
    
    public static Bitmap bitmapZoom(Bitmap bitmap) {
		Bitmap curBitmap = null;
        double maxSize = 200.00;  //图片允许最大空间 (KB)
        ByteArrayOutputStream bitmapStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bitmapStream);
        double curBitmapSize = bitmapStream.toByteArray().length / 1024;
        //判断bitmap占用空间是否大于maxSize 
        if (curBitmapSize > maxSize) {
            double scale = curBitmapSize / maxSize;
            curBitmap = changeBitampSize(bitmap, bitmap.getWidth() / Math.sqrt(scale), bitmap.getHeight() / Math.sqrt(scale));
        } else {
        	curBitmap = bitmap;
        }
        return curBitmap;
	}
	
	/***
     * bgimage  ：  图片资源
     * width    ：  目标宽度
     * height   ：  目标高度
     */
    public static Bitmap changeBitampSize(Bitmap bitmap, double width, double height) {
    	Matrix matrix = new Matrix();
        // 获取这个图片的宽和高
        float curWidth = bitmap.getWidth();
        float curHeight = bitmap.getHeight();
        // 计算宽高缩放率
        float scaleWidth = ((float) width) / curWidth;
        float scaleHeight = ((float) height) / curHeight;
        // 缩放图片
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap curBitmap = Bitmap.createBitmap(bitmap, 0, 0, (int) curWidth, (int) curHeight, matrix, true);
        return curBitmap;
    }
    
    /**
	 * 通过BitmapFactory.Options压缩图片
	 * @param inputStream1
	 * @param inputStream2
	 * @param requiredWidth
	 * @return  
	 */
	public static Bitmap decodeStream(InputStream inputStream1,
			InputStream inputStream2, int requiredWidth) {
		try {
			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inJustDecodeBounds = true;
			o.inPreferredConfig = Bitmap.Config.RGB_565;
			BitmapFactory.decodeStream(inputStream1, null, o);
			final int REQUIRED_SIZE = requiredWidth;
			int width_tmp = o.outWidth;
			int hight_tmp = o.outHeight;
			inputStream1.close();
			int scale = 2;
			while (true) {
				if (width_tmp / 2 < REQUIRED_SIZE || hight_tmp / 2 < REQUIRED_SIZE)
					break;
				width_tmp /= 2;
				hight_tmp /= 2;
				scale *= 2;
			}

			BitmapFactory.Options o2 = new BitmapFactory.Options();
			o2.inSampleSize = scale;
			Bitmap bitmap = BitmapFactory.decodeStream(inputStream2, null, o2);
			inputStream2.close();
			return bitmap;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 
	 * @param bmpOrg
	 * @param requestPx
	 * @param heightRequestFlag  false不按高压缩，ture按高判断压缩
	 * @return
	 */
	public static Bitmap getCompressBmp(Bitmap bmpOrg, int requestPx, boolean heightRequestFlag) {
		if (bmpOrg != null) {
			int width = bmpOrg.getWidth();
			int height = bmpOrg.getHeight();
			if (width != requestPx) {
				float wh = ((float) width) / height;
				int newWidth = 0;
				int newheight = 0;
				if (heightRequestFlag) {
					if (width > height) {
						newWidth = requestPx;
						newheight = (int) (newWidth / wh);
					} else {
						newheight = requestPx;
						newWidth = (int) (newheight * wh);
					}
				} else {
					newWidth = requestPx;
					newheight = (int) (newWidth / wh);
				}
				float sw = ((float) newWidth) / width;
				float sh = ((float) newheight) / height;
				Matrix matrix = new Matrix();
				matrix.postScale(sw, sh);
				Bitmap resizeBitmap = Bitmap.createBitmap(bmpOrg, 0, 0, width, height, matrix, true);
				if (!bmpOrg.isRecycled()) {
					bmpOrg.recycle();
					bmpOrg = null;
				}
				return resizeBitmap;
			}
			return bmpOrg;
		}
		return null;
	}
	
	/**
	 * Bitmap保存到本地
	 * @param bmpOrg
	 * @param fileDir
	 * @param fileName
	 * @param imageQuelity
	 * @throws Exception
	 */
	public static void compress(Context context, Bitmap bmpOrg,
			int imageQuelity, String file) throws Exception {
		bmpOrg.compress(Bitmap.CompressFormat.JPEG, imageQuelity,
				new FileOutputStream(file));
	}
	
	public static int getExifOrientation(String filepath) {
        int degree = 0;
        ExifInterface exif = null;
        try {
            exif = new ExifInterface(filepath);
        } catch (IOException ex) {
        	ex.printStackTrace();
        }
        if (exif != null) {
            int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, -1);
            if (orientation != -1) {
                switch(orientation) {
                    case ExifInterface.ORIENTATION_ROTATE_90:
                        degree = 90;
                        break;
                    case ExifInterface.ORIENTATION_ROTATE_180:
                        degree = 180;
                        break;
                    case ExifInterface.ORIENTATION_ROTATE_270:
                        degree = 270;
                        break;
                }
            }
        }
        return degree;
    }

}
